package com.kbt.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.android.volley.Request;
import com.google.gson.Gson;
import com.kbt.activity.GoodInfoActivity;
import com.kbt.activity.R;
import com.kbt.activity.StoreActivity;
import com.kbt.base.BaseApplication;
import com.kbt.commont.Constants;
import com.kbt.fragment.GoodCarEditFragment;
import com.kbt.listener.ClickChangeGoodCountListener;
import com.kbt.listener.ClickCheckGoodListener;
import com.kbt.listener.ClickStartActivityListener;
import com.kbt.model.data.*;
import com.kbt.model.holder.GoodForEditCarInfoHolder;
import com.kbt.net.RequestManager;
import com.kbt.util.data.StaticData;
import com.kbt.util.tool.CommonStatus;
import com.kbt.util.utils.ImageManager;
import com.kbt.util.utils.SharePreferenceUtils;
import com.kbt.util.utils.Utils;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhgk
 * @package: com.kbt.adapter
 * @TODO: <请描述这个类是干什么的>
 * @data: 2015/8/12 14:42
 * @version: V1.0
 */
public class GoodCarEditAdapter extends BaseAdapter {
    //商品数据列表
    private List<ShopCarBean> goodInfoList;
    //生命上下文
    private Activity context;
    //总价格
    private TextView totalView;
    //商品件数
    private TextView numberView;
    //应付总价
    private TextView payMoneyView;
    //商品总价
    private TextView totalMoneyView;
    //份数
    private List<HashMap<String, String>> numList = null;
    private ImageLoader imageLoader;
    private ShopCarListBean shopCarListBean;
    private List<ShopCarBean> shopCarBeans = new ArrayList<ShopCarBean>();

    public GoodCarEditAdapter(Activity context, List<ShopCarBean> goodInfoList, TextView totalView, TextView numberView, TextView payMoneyView, TextView totalMoneyView, List<HashMap<String, String>> numList) {
        this.goodInfoList = goodInfoList;
        this.context = context;
        this.totalView = totalView;
        this.numberView = numberView;
        this.payMoneyView = payMoneyView;
        this.totalMoneyView = totalMoneyView;
        this.numList = numList;
        this.imageLoader = ImageLoader.getInstance();
    }

    @Override
    public int getCount() {
        return goodInfoList.size();
    }

    @Override
    public Object getItem(int position) {
        return goodInfoList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    /**
     * 再次赋值
     *
     * @param mlist
     */
    public void setList(List<ShopCarBean> mlist) {
        goodInfoList = mlist;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        GoodForEditCarInfoHolder itemHolder;

        if (convertView == null) {
            itemHolder = new GoodForEditCarInfoHolder();

            LayoutInflater layoutInflater = LayoutInflater.from(context);
            convertView = layoutInflater.inflate(R.layout.good_car_edit_item, null);

            itemHolder.setGoodCheckBox((CheckBox) convertView.findViewById(R.id.car_good_check));
            itemHolder.setGoodImg((ImageView) convertView.findViewById(R.id.car_good_img));
            itemHolder.setGoodPrice((TextView) convertView.findViewById(R.id.car_good_price));
            itemHolder.setGoodCountEdit((EditText) convertView.findViewById(R.id.car_good_count_edit));
            itemHolder.setGoodCount((TextView) convertView.findViewById(R.id.car_good_count));

            itemHolder.setAddBtn((Button) convertView.findViewById(R.id.car_good_add_btn));
            itemHolder.setSubBtn((Button) convertView.findViewById(R.id.car_good_sub_btn));
            itemHolder.setDelBtn((Button) convertView.findViewById(R.id.car_good_del_btn));
            itemHolder.setKucun((TextView) convertView.findViewById(R.id.kucun));

            convertView.setTag(itemHolder);
        } else {
            itemHolder = (GoodForEditCarInfoHolder) convertView.getTag();
        }

        final ShopCarBean goodInfo = goodInfoList.get(position);

        itemHolder.getKucun().setText("库存:"+goodInfo.getStore_counts());
        if (goodInfo.getGoods_status().equals("1")) {
            itemHolder.getGoodCheckBox().setChecked(true);
        } else {
            itemHolder.getGoodCheckBox().setChecked(false);
        }
        imageLoader.displayImage(Constants.ServiceInterFace.imageURL + goodInfo.getGoods_icon(), itemHolder.getGoodImg(), ImageManager.getOptions(
                R.drawable.loadings, R.drawable.loadings));
        itemHolder.getGoodPrice().setText("" + goodInfo.getGoods_new_price());
        if (numList.size() > 0) {
            itemHolder.getGoodCount().setText("" + numList.get(position).get("number") + "");
            itemHolder.getGoodCountEdit().setText(numList.get(position).get("number") + "");
        }
        ClickChangeGoodCountListener subListener = new ClickChangeGoodCountListener(context, StaticData.BUTTON_SUB_BTN,
                itemHolder.getGoodCountEdit(), itemHolder.getGoodCount(),
                totalView, numberView, payMoneyView, totalMoneyView, goodInfo.getGoods_new_price(), StaticData.CHANG_EDIT_SHOW_TOTAL_COUNT, position, numList, goodInfo.getGoods_id(),goodInfo);
        itemHolder.getSubBtn().setOnClickListener(subListener);

        ClickChangeGoodCountListener addListener = new ClickChangeGoodCountListener(context, StaticData.BUTTON_ADD_BTN,
                itemHolder.getGoodCountEdit(), itemHolder.getGoodCount(),
                totalView, numberView, payMoneyView, totalMoneyView, goodInfo.getGoods_new_price(), StaticData.CHANG_EDIT_SHOW_TOTAL_COUNT, position, numList, goodInfo.getGoods_id(),goodInfo);
        itemHolder.getAddBtn().setOnClickListener(addListener);

        //删除Listener
        ClickDelGoodListener delListener = new ClickDelGoodListener(goodInfo.getGoods_id(), position, itemHolder.getGoodCountEdit(), goodInfo.getGoods_new_price(), totalView, numberView, payMoneyView, totalMoneyView,numList);
        itemHolder.getDelBtn().setOnClickListener(delListener);

        itemHolder.getGoodImg().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, GoodInfoActivity.class);
                intent.putExtra("shopId", goodInfo.getGoods_id() + "");
                context.startActivity(intent);
            }
        });

        return convertView;
    }


    /***
     * 删除按钮事件
     */
    private class ClickDelGoodListener implements View.OnClickListener, RequestManager.ResponseInterface {
        private int postion;
        private EditText goodCount;
        private double price;
        private RequestManager mRequestManager;
        private Map<String, String> map;
        private Map<String, Object> getMap;
        private String id;
        private BaseBean baseBean;
        private TextView totalView;
        private TextView numberView;
        private TextView payMoneyView;
        private TextView totalMoneyView;
        private SharePreferenceUtils share;
        private CountBean countBean;
        private List<HashMap<String, String>> numList=null;


        ClickDelGoodListener(String id, int postion, EditText goodCount, double price, TextView totalView, TextView numberView, TextView payMoneyView, TextView totalMoneyView,List<HashMap<String, String>> numList) {
            this.id = id;
            this.postion = postion;
            this.goodCount = goodCount;
            this.price = price;
            this.totalView = totalView;
            this.numberView = numberView;
            this.payMoneyView = payMoneyView;
            this.totalMoneyView = totalMoneyView;
            //初始化请求的管理器
            mRequestManager = new RequestManager();
            mRequestManager.setResponseListener(this);
            map = new HashMap<String, String>();
            getMap = new HashMap<String, Object>();
            share = new SharePreferenceUtils(context);
            this.numList = numList;
        }

        @Override
        public void onClick(View v) {
            dialog(postion);
        }

        private void dialog(int position) {
            AlertDialog.Builder bu = new AlertDialog.Builder(context);
            bu.setTitle("删除商品");
            bu.setMessage("放弃该商品的购买么？");
            bu.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    //删除购物车商品
                    httpDelete();
                }
            });

            bu.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                }
            });
            bu.setInverseBackgroundForced(true);
            bu.show();
        }

        //删除购物车商品
        private void httpDelete() {
            map.clear();
            map.put("methodType", "remove");
            Gson gson = new Gson();
            Map dataMap = new HashMap<String,String>();
            dataMap.put("user_mobile", share.getString("user_mobile", ""));
            dataMap.put("goods_id", id);
            map.put("data", gson.toJson(dataMap));
            mRequestManager.post(Constants.ServiceInterFace.deleteShopCarURL, map, Constants.RequestTag.deleteShopCarTag, BaseBean.class);
        }

        @Override
        public <T> void successResponse(T parsedGSON, int tag) {
            if (tag == Constants.RequestTag.deleteShopCarTag) {
                /** 判断返回值不为空 **/
                if (parsedGSON != null) {
                    baseBean = (BaseBean) parsedGSON;
                    if (baseBean.getResult().equals("success")) {
                        Toast.makeText(context, "删除成功!", Toast.LENGTH_SHORT).show();
                        ShopCarBean goodInfo = goodInfoList.get(postion);
                        if(goodInfo.getGoods_status().equals("1")) {
                        double total = BaseApplication.getInstance().shopCarTotal - Integer.parseInt(goodCount.getText().toString()) * price;
                        BaseApplication.getInstance().shopCarTotal = total;
                        totalMoneyView.setText(new BigDecimal(total).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                        double payMoney = total - BaseApplication.getInstance().discount + BaseApplication.getInstance().freight;
                        BaseApplication.getInstance().shopCarPayable = payMoney;
                        payMoneyView.setText(new BigDecimal(payMoney).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                        totalView.setText(new BigDecimal(payMoney).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                        BaseApplication.getInstance().shopCarNumber = BaseApplication.getInstance().shopCarNumber - Integer.parseInt(goodCount.getText().toString());
                        numberView.setText("已选择商品" + BaseApplication.getInstance().shopCarNumber + "件");
                        }
                        if (goodInfoList.size() == 1) {
                            BaseApplication.getInstance().shopCarTotal = 0;
                            totalMoneyView.setText(0 + "");
                            BaseApplication.getInstance().shopCarPayable = 0;
                            payMoneyView.setText(0 + "");
                            totalView.setText(0 + "");
                            BaseApplication.getInstance().shopCarNumber = 0;
                            numberView.setText("已选择商品" + BaseApplication.getInstance().shopCarNumber + "件");
                        }
//                        goodCount.setText(ClickChangeGoodCountListener.numList.get(postion).get("number")+"");
                        numList.remove(postion);
                        goodInfoList.remove(postion);
                        GoodCarEditAdapter.this.notifyDataSetChanged();
                        //去判断购物车中还有没有数据
                        httpShopCar();

                    } else {
                        Toast.makeText(context, baseBean.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                }
            }
            if (tag == Constants.RequestTag.selectShopCarTag) {
                if (parsedGSON != null) {
                    shopCarListBean = (ShopCarListBean) parsedGSON;
                    // 判断是否是有数据
                    if (shopCarListBean.getResult().equals("success")) {// 成功
                        if (shopCarListBean.getData().size() > 0) {//获取到数据
//                            if (goodInfoList.size() > 0) {
//                                CommonStatus.carStatus = "EDIT";
//                            } else {
//                                CommonStatus.carStatus = "COMPLETE";
//                            }
                                getShopType();
                        } else {
                            if (goodInfoList.size() == 0) {
                                CommonStatus.carStatus = "EMPTY";
                            }
                            Intent intent = new Intent(context, StoreActivity.class);
                            BaseApplication.getInstance().currentItem = StaticData.INDEX_CAR;
                            context.startActivity(intent);
                            context.finish();
                        }

                    }
                }
            }
            if (tag == Constants.RequestTag.selectShopCarZhongLeiTag) {
                if (parsedGSON != null) {
                    countBean = (CountBean) parsedGSON;
                    // 判断是否是有数据
                    if (countBean.getResult().equals("success")) {// 成功
                        BaseApplication.getInstance().shopType = countBean.getData();
                        StoreActivity.jianCarNumber();
                    }
                }
            }
        }

        @Override
        public void errorResonse(String retmeg, int tag) {
            Toast.makeText(context, "error!", Toast.LENGTH_SHORT).show();
        }

        private void httpShopCar() {
            mRequestManager.requestGet(Request.Method.GET, Constants.ServiceInterFace.selectShopCarURL + share.getString("user_mobile", "") + "&methodType=queryGoodsList", Constants.RequestTag.selectShopCarTag, getMap, ShopCarListBean.class);
        }
        //获取商品数量
        private void getShopType(){
            if(Utils.isNetworkAvailable(context)){
                mRequestManager.requestGet(Request.Method.GET, Constants.ServiceInterFace.selectShopCarZhongLeiURL + share.getString("user_mobile","")+"&methodType=queryGoodsSum", Constants.RequestTag.selectShopCarZhongLeiTag,getMap, CountBean.class);
            }else{
                Toast.makeText(context,R.string.Wangluo,Toast.LENGTH_SHORT).show();
            }
        }
    }


}
